package com.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * cookie缓存
 *
 *
 * Class Name   : Cookie
 *
 * @author yangguanzan
 * @version 0.0.1:Cookie 16:28Z  yangguanzan $
 * @data 2018/10/19.
 *
 * Modification    Log
 *
 * Date            Ver         Programmer     Description
 *
 * 2018/10/19         1.0         yangguanzan          Create
 */
public class CookieUtils {
  private CookieUtils() {
    // nothing
  }
  public static final String USERNAME="username";
  public static final String REMEMBER_ME="rememberMe";

  public static final int DAY_SECONDS=86400;

  public static void setUsername(HttpServletResponse response, String username) {
    setCookie(response,USERNAME,username,"/",30);
    setCookie(response,REMEMBER_ME,Boolean.TRUE.toString(),"/",30);
  }

  public static void removeUsername(HttpServletResponse response, String username) {
    setCookie(response,USERNAME,username,"/",0);
    setCookie(response,REMEMBER_ME,REMEMBER_ME,"/",0);
  }

  /**
   * 设置Cookie的值
   *
   * @param response 响应
   * @param key 键
   * @param value 键值
   * @param path 路径
   * @param day 有效天数
   * @return
   */
  public static void setCookie(HttpServletResponse response, String key,
      String value,String path,int day) {
    Cookie cookie = new Cookie(key, value);
    // 保存天数
    cookie.setMaxAge(DAY_SECONDS*day);
    cookie.setPath(path);
    // 在 setSecure(true) 的情况下，只有https才传递到服务器端。http是不会传递的。
    // 当 setSecure(true) 时，浏览器端的cookie不会传递到服务器端。
    // 当 setSecure(true) 时，服务器端的cookie会传递到浏览器端
    cookie.setSecure(true);
    response.addCookie(cookie);
  }

  /**
   * 获取Cookie里的用户名
   *
   * @param request 请求
   * @return 用户名
   */
  public static String getUsername(HttpServletRequest request) {
    return getCookieByKey(request,USERNAME);
  }

  /**
   * 根据key获取Cookie的值
   *
   * @param request 请求
   * @param key 键
   * @return 键值
   */
  public static String getCookieByKey(HttpServletRequest request,String key) {
    if(null==key||"".equals(key)){
      return null;
    }

    Cookie[] cookies = request.getCookies();
    if(null==cookies||cookies.length==0){
      return null;
    }

    Cookie[] arr = cookies;
    Cookie cookie=null;
    int len = cookies.length;
    for(int i = 0; i < len; ++i) {
        cookie = arr[i];
        if(key.equals(cookie.getName())) {
          return cookie.getValue();
        }
    }
    return null;
  }
}